/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package propertymgmt.gui;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import propertymgmt.entities.Property;
import propertymgmt.util.PropertiesManager;

/**
 * PropertyImageFrame.java
 * 
 * Allows the user to display and set the Image associated
 * with a Property.
 *
 * @author Brian
 */
@SuppressWarnings("serial")
public class PropertyImageFrame extends javax.swing.JInternalFrame {
	
	private Property property = null;
	private FileFilter imageFileFilter =
			new FileNameExtensionFilter("Image Files", ImageIO.getReaderFileSuffixes());
	
    /**
     * Creates new form PropertyImageFrame
     */
    public PropertyImageFrame(Property property) {
    	this.property = property;
        initComponents();
        setTitle(property.getPropertyName() + " Image");
        if(property.getImageBytes() != null){
        	setImage();
        }
    }

    private void initComponents() {
    	lbl_image = new javax.swing.JLabel();
        btn_setImage = new javax.swing.JButton();
        btn_clearImage = new javax.swing.JButton();

        setClosable(true);

        lbl_image.setBorder(new javax.swing.border.MatteBorder(null));
        lbl_image.setPreferredSize(new java.awt.Dimension(750, 622));

        btn_setImage.setText("Set Image");
        btn_setImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_setImageActionPerformed(evt);
            }
        });

        btn_clearImage.setText("Clear Image");
        btn_clearImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_clearImageActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbl_image, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btn_setImage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btn_clearImage, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbl_image, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btn_setImage, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btn_clearImage, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );

        pack();
    }// </editor-fold>       
    
    private void setImage(){
    	int w = (int) lbl_image.getPreferredSize().getWidth();
    	int h = (int) lbl_image.getPreferredSize().getHeight();
		try {
			BufferedImage buffImage = ImageIO.read(new ByteArrayInputStream(property.getImageBytes()));
        	BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
        	Graphics2D g2 = resizedImg.createGraphics();
        	g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        	g2.drawImage(buffImage, 0, 0, w, h, null);
        	g2.dispose();

        	ImageIcon imageIcon = new ImageIcon(resizedImg);
        	lbl_image.setIcon(imageIcon);
        	PropertiesManager.getInstance().saveDbState();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this, "Error reading image", "Error", JOptionPane.ERROR_MESSAGE);
		}
    }

    private void btn_clearImageActionPerformed(java.awt.event.ActionEvent evt) {
    	if(property.getImageBytes() != null){
    		property.setImageBytes(null);
    		lbl_image.setIcon(null);
    		PropertiesManager.getInstance().saveDbState();
    	}
    }                                        

    private void btn_setImageActionPerformed(java.awt.event.ActionEvent evt) {
    	JFileChooser chooser = new JFileChooser("./");
    	chooser.setFileFilter(imageFileFilter);
    	chooser.setAcceptAllFileFilterUsed(false);
    	
    	if(chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
    		File imageFile = chooser.getSelectedFile();
    		try {
				BufferedImage newImage = ImageIO.read(imageFile);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ImageIO.write(newImage, "jpg", baos);
				byte imageBytes[] = baos.toByteArray();
				property.setImageBytes(imageBytes);
				setImage();
			} catch (IOException e) {
				JOptionPane.showMessageDialog(this, "Error reading image", "Error", JOptionPane.ERROR_MESSAGE);
			}
    	}
    }                                            

    // Variables declaration - do not modify                     
    private javax.swing.JButton btn_clearImage;
    private javax.swing.JButton btn_setImage;
    private javax.swing.JLabel lbl_image;
    // End of variables declaration                   
}